package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void saveWithFlavors(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish); //此为第一次新增菜品 dishDTO中没有id属性
        dishMapper.insert(dish);
        Long dishId = dish.getId(); // 插入菜品数据后获取mybatis回传的菜品主键id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> flavor.setDishId(dishId));
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 分页查询 3板斧
     *
     * @param dishPageQueryDTO 除了page和pageSize以外，另有name categoryId status 3个属性作为sql查询的条件
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 返回结果泛型为DishVO 除封装全部的Dish表属性外 还有一个categoryName属性
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        // 判断当前要删除的菜品状态是否为起售中
        ids.forEach(id -> {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        // 判断当前要删除的菜品是否被套餐关联了
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品数据的同时也要删除菜品所关联的口味数据
        ids.forEach(id -> {
            dishFlavorMapper.deleteByDishId(id);
            dishMapper.deleteById(id);
        });
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        DishVO dishVO = new DishVO();

        Dish dish = dishMapper.getById(id);
        List<DishFlavor> flavors = dishFlavorMapper.getByDishId(id);

        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    // 与新增菜品不同的是修改餐品时已经能够直接通过dishDTO获取菜品的id属性了
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {
        // 修改菜品数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        // 根据菜品id删除菜品关联的旧口味
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        // 新增菜品关联口味
        List<DishFlavor> flavors = dishDTO.getFlavors();
        // 将菜品id赋给遍历赋给flavors 执行修改数据库操作须注意是否有某些键没有被赋值
        if (flavors != null && flavors.size() > 0) {
            flavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    @Transactional
    @Override
    public void startOrStop(int status, Long id) {
        // 菜品起售禁售
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);
        // 若执行的是禁售操作 那么与菜品关联的套餐也应禁售
        //SetMealDishMapper中已经有了根据菜品id集批量查询关联套餐的sql查询语句
        if (status == StatusConstant.DISABLE) {
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            //SetmealDish表是菜品与套餐的多对多映射表
            // 根据菜品id批量查询关联的套餐id集 数量应不止一个
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(dishIds);
            setmealIds.forEach(setmealId -> {
                //设定套餐id和状态封装为一个套餐对象
                Setmeal setmeal = Setmeal.builder()
                        .id(setmealId)
                        .status(StatusConstant.DISABLE)
                        .build();
                setmealMapper.update(setmeal);
            });

        }

    }

    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        //构建dish查询对象
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE) // 限定查询在售中的菜品
                .build();
        return dishMapper.list(dish);
    }

    @Override
    public List<DishVO> listWithFlavor(Long categoryId) {
        // 封装作为查询条件的dish对象
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE) // 查询的菜品需为起售状态
                .build();

        // 根据查询条件批量获取dish数据
        List<Dish> dishList = dishMapper.list(dish);
        // 遍历每个dish，查询出每个dish所包含的口味数据并封装到DishVO数组中
        List<DishVO> list = new ArrayList<>();

        dishList.forEach(d -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            list.add(dishVO);
        });
        return list;
    }

}
